﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using BusinessLogicLayer;
using DataAccessLayer;
using DataAccessLayer.ImportDataSetTableAdapters;


namespace PresentationLayer
{
    public partial class DialogImport03 : Form
    {
        private OleDbDatabase.MappingTaskID mappingTaskID;
        private string excelFile;

        private int lastSavedDistributorID;

        DataTable listColumnAvailableDataTable;


        public DialogImport03(OleDbDatabase.MappingTaskID mappingTaskID, string excelFile)
        {
            InitializeComponent();

            this.mappingTaskID = mappingTaskID;
            this.excelFile = excelFile;
            Global.Class.Library.GlobalVariables.ImportNextStep = 0;

            this.listColumnAvailableDataTable = new DataTable("ListColumnAvailable");
            this.listColumnAvailableDataTable.Columns.Add("SerialID", System.Type.GetType("System.Int32"));
            this.listColumnAvailableDataTable.Columns.Add("ColumnAvailableName", System.Type.GetType("System.String"));

        }

        private void DialogMapExcelColumn_Load(object sender, EventArgs e)
        {
            try
            {
                //Get available column from current file
                DataTable excelDataTable = OleDbDatabase.OpenExcelSheet(this.excelFile, OleDbDatabase.GetMappingSheetName(this.mappingTaskID), "TOP 1 *");
                if (excelDataTable != null && excelDataTable.Columns.Count > 0)
                {
                    int i = 0;
                    foreach (DataColumn dataColumn in excelDataTable.Columns)
                    {
                        DataRow dataRow = this.listColumnAvailableDataTable.NewRow();
                        dataRow["SerialID"] = ++i;
                        dataRow["ColumnAvailableName"] = dataColumn.ColumnName;
                        this.listColumnAvailableDataTable.Rows.Add(dataRow);
                    }
                }


                this.dataGridColumnAvailable.AutoGenerateColumns = false;
                this.dataGridColumnAvailable.DataSource = this.listColumnAvailableDataTable;

                StackedHeaderDecorator stackedHeaderDecorator = new StackedHeaderDecorator(this.dataGridColumnAvailable);

                CommonMetaList commonMetaList = new CommonMetaList();
                ERmgrUIP.ListDistributorNameDataTable listDistributorNameDataTable = commonMetaList.GetDistributorName(true);
                this.comboBoxDistributorID.DataSource = listDistributorNameDataTable;
                this.comboBoxDistributorID.DisplayMember = listDistributorNameDataTable.DescriptionOfficialColumn.ColumnName;
                this.comboBoxDistributorID.ValueMember = listDistributorNameDataTable.DistributorIDColumn.ColumnName;

                this.lastSavedDistributorID = this.GetMappingFile(); //Intelligence initial DistributorID by compare current file with last saved file
                this.comboBoxDistributorID.SelectedValue = this.lastSavedDistributorID;

            }
            catch (Exception exception)
            {
                GlobalExceptionHandler.ShowExceptionMessageBox(this, exception);
            }
        }

        private int GetMappingFile()
        {
            try
            {
                ListDistributorFileTableAdapter listDistributorFileTableAdapter = new ListDistributorFileTableAdapter();
                ImportDataSet.ListDistributorFileDataTable listDistributorFileDataTable = listDistributorFileTableAdapter.GetDataDistinctDistributorID();

                foreach (ImportDataSet.ListDistributorFileRow listDistributorFileRow in listDistributorFileDataTable.Rows)
                {
                    ImportDataSet.ListDistributorFileDataTable listDistributorFile = listDistributorFileTableAdapter.GetDataByDistributorID(listDistributorFileRow.DistributorID);
                    for (int i = 0; i < listDistributorFile.Rows.Count; i++)
                    {
                        if (((ImportDataSet.ListDistributorFileRow)listDistributorFile.Rows[i]).ColumnName != "")
                        {
                            DataRow[] foundDataRows = this.listColumnAvailableDataTable.Select("ColumnAvailableName = '" + ((ImportDataSet.ListDistributorFileRow)listDistributorFile.Rows[i]).ColumnName + "'");
                            if (foundDataRows == null || foundDataRows.Length == 0) break;
                        }

                        if (i == listDistributorFile.Rows.Count - 1) { return listDistributorFileRow.DistributorID; }
                    }
                }

                return 0;
            }
            catch
            {
                return 0;
            }
        }


        private void toolStripButtonEscapeAndNext_Click(object sender, EventArgs e)
        {
            try
            {
                if (sender.Equals(this.toolStripButtonNext))
                {
                    if (this.comboBoxDistributorID.SelectedIndex < 0 || (int)this.comboBoxDistributorID.SelectedValue == 0) throw new Exception("Please select a distributor.");

                    Global.Class.Library.GlobalVariables.DistributorID = (int)this.comboBoxDistributorID.SelectedValue;

                    if (Global.Class.Library.GlobalVariables.DistributorID != this.lastSavedDistributorID)
                    {
                        DialogResult dialogResult = MessageBox.Show(this, "Are you sure this Excel file belong to " + this.comboBoxDistributorID.Text + "?", "Please check your Excel file carefully before continue.", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
                        if (dialogResult == DialogResult.No) { this.DialogResult = DialogResult.None; return; }
                    }

                    if (this.lastSavedDistributorID > 0) SQLDatabase.ExecuteNonQuery("DELETE FROM ListDistributorFile WHERE DistributorID = " + this.lastSavedDistributorID);//UNDO DETAILS
                    SQLDatabase.ExecuteNonQuery("DELETE FROM ListDistributorFile WHERE DistributorID = " + Global.Class.Library.GlobalVariables.DistributorID); //UNDO DETAILS

                    for (int i = 0; i < listColumnAvailableDataTable.Rows.Count; i++)
                    {
                        SQLDatabase.ExecuteNonQuery("INSERT INTO ListDistributorFile (DistributorID, SerialID, ColumnName, ImportDate) VALUES (" + Global.Class.Library.GlobalVariables.DistributorID + ", " + i + ", N'" + listColumnAvailableDataTable.Rows[i]["ColumnAvailableName"].ToString() + "', CONVERT(smalldatetime, '" + DateTime.Today.ToString("dd/MM/yyyy") + "',103))");
                    }

                    Global.Class.Library.GlobalVariables.ImportNextStep = 1;

                    this.DialogResult = DialogResult.OK;
                }

                if (sender.Equals(this.toolStripButtonEscape))
                    this.DialogResult = DialogResult.Cancel;


            }
            catch (Exception exception)
            {
                GlobalExceptionHandler.ShowExceptionMessageBox(this, exception);
            }
        }


    }
}
